package com.pf.core.xml;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import org.w3c.dom.Node;

import com.pf.core.controller.Controller;
import com.pf.core.pojo.Config;
import com.pf.core.pojo.MVC;
import com.pf.core.util.PfNodeUtil;
import com.pf.core.util.ReflectUtil;
import com.pf.core.util.StringUtil;

public class PfSysConfigParser {
	private PfNodeParser parser=new PfNodeParser();
	public PfSysConfigParser(){
		getMVC();
		getInit();
		getBasePath();
		getViewPath();
		getEncode();
	}

	public void parse(InputStream inputStream) throws Exception{
       parser.parse(inputStream);
	}

	private void getMVC(){
		parser.addNodelet("/pf/mvc", new PfNode(){
			public void execute(Node node) {
				Map<String,String> map=PfNodeUtil.getAtts(node);
				try {
					MVC mvc=new MVC();
					if(!StringUtil.isBlank(map.get("controller"))){
						mvc.setController((Controller)(Class.forName(map.get("controller")).newInstance()));
					}

					if(!StringUtil.isBlank(map.get("urlMapping"))){
						mvc.setUrlMapping(map.get("urlMapping"));
					}

					if(!StringUtil.isBlank(map.get("errorPage"))){
						mvc.setErrorPage(map.get("errorPage"));
					}
					Config.getInstance().setMvc(mvc);
				} catch (Exception e) {

				}
			}
		});

	}


	private void getInit(){
		parser.addNodelet("/pf/init/class/text()", new PfNode(){
			public void execute(Node node) {
				if(!StringUtil.isBlank(node.getNodeValue())){
					Config.getInstance().getInitList().add(node.getNodeValue());
				}

			}
		});

	}

	private void getBasePath(){
		parser.addNodelet("/pf/basePath/text()", new PfNode(){

			public void execute(Node node) {
				if(!StringUtil.isBlank(node.getNodeValue())){
					Config.getInstance().setBasePath(node.getNodeValue());
				}

			}

		});
	}

	private void getViewPath(){
		parser.addNodelet("/pf/view/text()", new PfNode(){
			public void execute(Node node) {
				if(!StringUtil.isBlank(node.getNodeValue())){
					Config.getInstance().setViewPath(node.getNodeValue());
				}

			}

		});
	}

	private void getEncode(){
		parser.addNodelet("/pf/encode/text()", new PfNode(){
			public void execute(Node node) {
				if(!StringUtil.isBlank(node.getNodeValue())){
					Config.getInstance().setEncode(node.getNodeValue());
				}

			}

		});
	}


	public static void main(String[] args)throws Exception{
		InputStream in = new BufferedInputStream(new FileInputStream("F:\\workspace\\yufuka\\platform\\WebRoot\\WEB-INF\\config\\pf.xml"));
		new PfSysConfigParser().parse(in);
		Config config=Config.getInstance();


	}

}
